<?php


namespace Drupal\shushengyuan\Schemas;


use Drupal\shusy_product\Entity\ShusyProduct;
use EntityListWrapper;

abstract class AbstractBaseModel {

  protected $context;

  protected $entity_id;

  protected $entity;

  protected $wrapper;

  protected $value = [];

  protected function cacheGet($cid, bool $autoDel = FALSE) {
    $cache = cache_get($cid, 'cache_shushengyuan');
    if (!empty($cache) && $autoDel) {
      $this->cacheDel($cid);
    }
    return $cache;
  }

  protected function cacheDel($cid) {
    cache_clear_all($cid, 'cache_shushengyuan');
  }

  protected function cacheSet($cid, $data, $expire = CACHE_PERMANENT) {
    return cache_set($cid, $data, 'cache_shushengyuan', $expire);
  }

  protected function cacheClear($cid) {
    cache_clear_all($cid, 'cache_shushengyuan');
  }

  final public function __construct() {
  }

  final static function init($entity_id, $reset = FALSE, $context = NULL) {
    $class = new static();
    return $class->_init_($entity_id, $reset, $context);
  }

  final protected function _init_($entity_id, $reset, $context) {
    $this->entity_id = $entity_id;
    $this->context = $context;
    $entity_type = $this->getEntityType();
    if ($entity_type) {
      $this->entity = $this->entityLoad($entity_type, $entity_id, $reset);
      if (!empty($this->entity)) {
        $this->wrapper = entity_metadata_wrapper($entity_type, $this->entity);
      }
      else {
        return FALSE;
      }
    }
    return $this->getValue();
  }

  abstract protected function getEntityType();

  protected function entityLoad($entity_type, $entity_id, $reset) {
    $entities = entity_load($entity_type, [$entity_id], [], $reset);
    return reset($entities);
  }

  final function getValue() {
    $this->setValue();
    return $this->value;
  }

  abstract protected function setValue();

  final static function get($entity_id, $reset = FALSE, $context = NULL) {
    $class = new static();
    return $class->_init_($entity_id, $reset, $context);
  }

  final protected function merge(array $value) {
    $this->value = array_merge($this->value, $value);
    return $this;
  }

  protected function convertYuan($amount) {
    return bcdiv($amount, 100, 2) + 0;
  }

  protected function imageStyleUrl($style_name, $uri) {
    $name = strtolower($style_name);
    $styles = image_styles();
    if (!isset($styles[$name])) {
      image_style_save([
        'name' => $name,
        'label' => $style_name,
      ]);
    }
    return image_style_url($name, $this->getUri($uri));
  }

  protected function getImgs($images, $style1 = 'imgs', $style2 = 'simgs') {
    $field_images = $images;
    $imgs = [];
    $sImgs = [];
    if ($field_images instanceof EntityListWrapper) {
      foreach ($field_images->getIterator() as $item) {
        $img = $item->value();
        $imgs[] = $this->imageStyleUrl($style1, $img['uri']);
        $sImgs[] = $this->imageStyleUrl($style2, $img['uri']);
      }
    }
    return [$imgs, $sImgs];
  }

  private function getUri($uri) {
    if (is_string($uri)) {
      return $uri;
    }
    if (is_array($uri) && isset($uri['uri'])) {
      return $uri['uri'];
    }
    if (is_object($uri) && isset($uri->uri)) {
      return $uri->uri;
    }
    return '';
  }

  protected function formatDate($timestamp, $format) {
    return format_date($timestamp, 'custom', $format);
  }

  /**
   * @param \Drupal\shusy_product\Entity\ShusyProduct $product
   *
   * @return float|int
   * 计算适用分类
   *
   * @deprecated 使用 hook_shushengyuan_product_amount_view_alter 替代
   */
  protected function getDiscount(ShusyProduct $product) {
    return 1;
  }

  final protected function getUid() {
    return $GLOBALS['user']->uid;
  }

  /**
   * @param $image
   * @param array $vars 变量表
   *
   * 基于变量表生成海报
   */
  protected function posterGenerateVars($image, array $vars) {
    $path = drupal_get_path('module', 'shushengyuan');
    $fontfile = "{$path}/fonts/alibaba/Alibaba-PuHuiTi-Medium.ttf";
    module_load_include('inc', 'image_effects_text', 'image_effects_text');
    foreach ($vars as $var) {
      switch ($var['type']) {
        case 'text':
          image_effects_text_effect_inc($image, [
            'text_source' => 'text',
            'text' => $var['text'],
            'fontfile' => $fontfile,
            'size' => $var['size'],
            //['HEX' => '#333333'],
            'RGB' => $var['rgb'],
            'alpha' => 100,
            'xpos' => $var['xpos'],
            'ypos' => $var['ypos'],
            'halign' => 'left',
            'valign' => 'top',
            'angle' => 0,
          ]);
          break;
        case 'overlay':
          $qr = imagecache_actions_image_load($var['uri']);
          image_scale($qr, $var['size'], $var['size'], TRUE);
          //添加二维码
          image_overlay($image, $qr, $var['xpos'], $var['ypos'], 100);
          break;
        case 'overlay_mask':
          $qr = imagecache_actions_image_load($var['uri']);
          image_scale($qr, $var['size'], $var['size'], TRUE);
          //添加二维码
          canvasactions_imagemask_effect($qr, ['path' => $var['mask']]);
          image_overlay($image, $qr, $var['xpos'], $var['ypos'], 100);
          break;
        case 'customtext':
          $sets = [
            'size' => 16,
            'color' => '#ffffff',
            'left' => 0,
            'bottom' => 0,
            'text' => "",
            'width' => 0,
            'height' => 0,
          ];
          $sets = $var['sets'];
          $ratio = 1;
          $path = drupal_get_path('module', 'shushengyuan');
          $fontfile = "{$path}/fonts/alibaba/Alibaba-PuHuiTi-Medium.ttf";
          $text = $sets['text'];
          $width = ($sets['width'] ?? 0) * $ratio;
          $height = ($sets['height'] ?? 0) * $ratio;
          $content = "";
          $letter = [];
          // 将字符串拆分成一个个单字 保存到数组 letter 中
          for ($i = 0; $i < mb_strlen($text); $i++) {
            $letter[] = mb_substr($text, $i, 1);
          }
          foreach ($letter as $l) {
            $teststr = $content . "" . $l;
            $fontBox = imagettfbbox($sets['size'] * $ratio, 0, $fontfile, $teststr);
            // 判断拼接后的字符串是否超过预设的宽度
            if (($fontBox[2] > $width) && ($content !== "")) {
              $content .= "\n";
            }
            //检查高度 超过高度 需要移除最后的几个字符 换成 ...
            if ($fontBox[3] >= $height) {
              $content = mb_substr($content, 0, mb_strlen($content) - 4);
              $content .= '...';
              break;
            }
            $content .= $l;
          }
          module_load_include('inc', 'image_effects_text', 'image_effects_text');
          $left = $sets['left'] * $ratio;
          $bottom = $sets['bottom'] * $ratio;
          $size = $sets['size'] * $ratio;
          image_effects_text_effect_inc($image, [
            'text_source' => 'text',
            'text' => (string) $content,
            'fontfile' => $fontfile,
            'size' => $size,
            'RGB' => ['HEX' => $sets['color']],
            'alpha' => 100,
            'xpos' => "left+{$left}",
            'ypos' => "bottom-{$bottom}",
            'halign' => 'left',
            'valign' => 'bottom',
            'angle' => 0,
          ]);
          break;
        case 'avatar':
          $sets = [
            'size' => 300,
            'left' => 0,
            'bottom' => 0,
            //square 圆角方形 circle 圆形
            'mode' => 'circle',
            'uri' => '',
          ];
          $sets = $var['sets'];
          $uri = $sets['uri'];
          $ratio = 1;
          $size = $sets['size'] * $ratio;
          $left = $sets['left'] * $ratio;
          $bottom = $sets['bottom'] * $ratio;

          $qrImage = imagecache_actions_image_load($uri);
          //缩放头像 蒙版尺寸 400*400
          image_scale($qrImage, 400, 400, TRUE);
          $mode = $sets['mode'];
          $path = drupal_get_path('module', 'shushengyuan');
          //给头像添加蒙板
          canvasactions_imagemask_effect($qrImage, ['path' => "{$path}/mask/mask_{$mode}.png"]);
          //缩放尺寸
          image_scale($qrImage, $size, NULL, TRUE);
          //添加头像
          image_overlay($image, $qrImage, "left+{$left}", "bottom+{$bottom}", 100);
          break;
        case 'image':
          $sets = [
            'size' => 300,
            'left' => 0,
            'bottom' => 0,
            'uri' => '',
          ];
          $sets = $var['sets'];
          $uri = $sets['uri'];
          $ratio = 1;
          $size = $sets['size'] * $ratio;
          $left = $sets['left'] * $ratio;
          $bottom = $sets['bottom'] * $ratio;
          $qrImage = imagecache_actions_image_load($uri);
          image_scale($qrImage, $size, NULL, TRUE);
          image_crop($qrImage, 0, 0, $size, $size);
          //添加头像
          image_overlay($image, $qrImage, "left+{$left}", "bottom+{$bottom}", 100);
          break;
      }
    }
  }

  protected function isDev() {
    if (variable_get_value('wx_mini_program:mini:dev')) {
      return TRUE;
    }
    return FALSE;
  }

  protected function getAvatar() {
    $account = user_load($this->getUid());
    $wrapper = entity_metadata_wrapper('user', $account);
    $avatar = $wrapper->youji_userwxinfo->avatar_file->value();
    if (!empty($avatar)) {
      return $avatar->uri;
    }
    $default_avatar = variable_get_value('youji_userwxinfo:default-avatar');
    $default_avatar_file = file_load($default_avatar);
    return $default_avatar_file->uri;
  }

}
